package com.calm.cthreadpool;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Create by Calm
 * on 2019/8/12
 */
public class CScheduleThreadPool extends AppCompatActivity {
    private final static String TAG = CScheduleThreadPool.class.getSimpleName();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cfixedthreadpool);
        findViewById(R.id.start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startTheadPool();
            }
        });
    }
    private void startTheadPool(){
        //ScheduledExecutorService(N) 有N条核心线程且有非限制的非核心线程，非核心线程闲置时会被立即回收。
        //主要用于执行定时任务和具有固定周期的重复任务
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
        for (int i = 0; i < 10; i++){
            final int index = i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    Log.e(TAG,"CScheduleThreadPool Start Run: 任务 = "+index+",线程 = "+Thread.currentThread().getName());
                    try {
                        Thread.sleep(2000);
                    }catch (InterruptedException e){

                    }
                }
            };
            //延迟2秒执行runnable
            executorService.schedule(runnable,2000, TimeUnit.MILLISECONDS);
        }
    }
}
